﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AliyunOss;
using QuDao;
using Kalman;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Bmp;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Processing;

namespace AdminUI.Controllers
{
    /// <summary>
    /// UMEditor上传图片
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ImageController : ControllerBase
    {
        readonly AliyunOssClient oss;
        public ImageController(AliyunOssClient aliyunOssClient)
        {
            oss = aliyunOssClient;
        }

        [HttpGet]
        public string Test()
        {
            return DateTime.Now.ToString();
        }

        [HttpGet, HttpPost]
        public void Upload()
        {
            /*
             * {
                "state": "SUCCESS",
                "original": "80px - \u526f\u67.jpg",
                "size": "13252",
                "title": "1465.jpg",
                "type": ".jpg",
                "url": "/ueditor/jsp/upload/image/20112/146075274.jpg"
                }
             */
            var json = new JObject
            {
                ["state"] = "FALSE",
                ["original"] = "asd",
                ["size"] = "0",
                ["title"] = "",
                ["type"] = "",
                ["url"] = "",
            };

            if(Request.Method != "POST" || Request.Form.Files.Count == 0)
            {
                Response.WriteAsync(json.ToString());//输出结果
                return;
                //return json.ToString();
            }

            var maxWidth = 720;
            var file = Request.Form.Files[0];

            var fileID = IDGenerator.Instance.GetFileID();
            var extName = Path.GetExtension(file.FileName);

            using (var stream = file.OpenReadStream())
            {
                //using var img = Image.Load(stream, out IImageFormat format);
                using var img = Image.Load(stream);
                var format = img.Metadata.DecodedImageFormat;
                var height = img.Height;
                if (img.Width > maxWidth) //自动转换图片大小
                {
                    img.Mutate(o =>
                    {
                        o.Resize(maxWidth, height * maxWidth / img.Width);
                    });
                }

                using var ms = new MemoryStream();
                switch (format)
                {
                    case GifFormat:
                        extName = ".gif";
                        img.SaveAsGif(ms);
                        break;
                    case JpegFormat:
                        extName = ".jpg";
                        img.SaveAsJpeg(ms, new JpegEncoder { Quality = 75 });
                        break;
                    case PngFormat:
                        extName = ".png";
                        img.SaveAsPng(ms, new PngEncoder { CompressionLevel = PngCompressionLevel.DefaultCompression });//默认Level6压缩级别
                        break;
                    default:
                        extName = ".png";
                        img.Save(ms, new PngEncoder { CompressionLevel = PngCompressionLevel.DefaultCompression });//默认Level6压缩级别
                        break;
                }
                ms.Seek(0, SeekOrigin.Begin);

                var ossKey = $"qudao/image-{DateTime.Now:yyyyMM}/{fileID}{extName}";
                var ossUrl = oss.Options.BindDomainUrl + ossKey;
                var fileSize = ms.Length;

                oss.PutImage(ossKey, ms);

                json["state"] = "SUCCESS";
                json["original"] = file.FileName;
                json["size"] = fileSize;
                json["type"] = extName;
                json["title"] = ossKey;
                json["url"] = ossUrl;
                json["code"] = 0;

                Response.ContentType = "text/html; charset=UTF-8";
                Response.WriteAsync(json.ToString());//输出结果
                //return json.ToString();
            }

        }
    }
}
